package exception

import (
	"fmt"
	"runtime"
	"strings"

	"github.com/astaxie/beego/logs"
)

func Stack() []byte {
	buf := make([]byte, 1024)
	for {
		n := runtime.Stack(buf, false)
		if n < len(buf) {
			return buf[:n]
		}
		buf = make([]byte, 2*len(buf))
	}
}

func StackOK() string {
	stack := ""
	data := Stack()
	lines := strings.Split(string(data), "\n")
	for i, _ := range lines {
		if i > 0 && i < 9 {
			continue
		}
		stack += lines[i] + "\n"
	}
	return stack
}

func GetInfo() (info string) {
	info = fmt.Sprintln("GO Version:", runtime.Version())
	info += fmt.Sprintln("ARCH:", runtime.GOARCH)
	info += fmt.Sprintln("OS:", runtime.GOOS)
	info += fmt.Sprintln("Number CPU:", runtime.NumCPU())
	info += fmt.Sprintln("Routine:", runtime.NumGoroutine())
	m := runtime.MemStats{}
	runtime.ReadMemStats(&m)
	if m.Alloc < 1024 {
		info += fmt.Sprintf("Malloc memory: %d bytes\n", m.Alloc)
	} else if m.Alloc < 1024*1024 {
		info += fmt.Sprintf("Malloc memory: %.3f K bytes\n", float64(m.Alloc)/1024)
	} else {
		info += fmt.Sprintf("Malloc memory: %.3f M bytes\n", float64(m.Alloc)/1024/1024)
	}
	info += "\n" + StackOK()
	return
}

func CatchException() {
	if err := recover(); err != nil {
		logs.Error("\nException:",
			err, "\n", GetInfo())
		logs.GetBeeLogger().Flush()
	}
}
